<template>
  <button class="back-home-btn" @click="goHome">← 返回首页</button>
  <div class="train-header">
    <h1>风行旅途</h1>
    <p class="subtitle">请确认车次信息并填写乘客信息</p>
  </div>
  <!-- 🚆 车次信息区域 -->
  <div class="train-card">
    <div class="stations">
      <div class="station from">
        <span class="city">{{ from }}</span>
      </div>
      <div class="train-middle">
        <div class="duration">{{ duration }}</div>
        <svg class="arrow-svg" viewBox="0 0 80 10" xmlns="http://www.w3.org/2000/svg">
          <line x1="0" y1="5" x2="70" y2="5" stroke="#111" stroke-width="2" />
          <polygon points="70,2 80,5 70,8" fill="#111" />
        </svg>
        <div class="train-no">{{ trainNumber }}</div>
      </div>
      <div class="station to">
        <span class="city">{{ to }}</span>
      </div>
    </div>
    <div class="train-extra">
      <span>座位类型：{{ seatType }}</span>
      <span>价格：￥{{ price }}</span>
    </div>
  </div>
  <!-- 👤 乘客信息 -->
  <div class="passenger-section-wrapper section">
    <div class="section-header column-layout">
      <h2>乘客信息</h2>
      <div class="selected-passengers" v-if="selectedPassengers.length > 0">
        <div class="passenger-display-scroll">
          <div v-for="(p, i) in selectedPassengers" :key="i" class="passenger-brief">
            <button class="remove-btn" @click="removePassenger(i)" title="移除乘客">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                <path
                  fill="currentColor"
                  d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm4.3 13.3-1.4 1.4L12 13.4l-2.9 2.9-1.4-1.4L10.6 12 7.7 9.1l1.4-1.4L12 10.6l2.9-2.9 1.4 1.4L13.4 12l2.9 2.9z"
                />
              </svg>
            </button>
            <div style="text-align: left">
              <p>
                <strong>{{ p.name }}</strong>
              </p>
              <p>身份证:{{ p.idCard }}</p>
            </div>
          </div>
        </div>
      </div>
      <button class="btn add-btn" @click="showAddPassenger = true">+ 新增乘客</button>
      <button class="btn select-btn" @click="fetchPassengers">选择已有乘客</button>
    </div>
  </div>
  <!-- 添加乘客弹窗 -->
  <div v-if="showAddPassenger" class="modal-overlay">
    <div class="modal">
      <button class="close" @click="closeModal">×</button>
      <div class="passenger-form-body">
        <input type="text" v-model="newPassenger.name" placeholder="请输入姓名" class="input" />
        <input
          type="text"
          v-model="newPassenger.idCard"
          placeholder="请输入身份证号码"
          class="input"
        />
        <input type="text" v-model="newPassenger.phone" placeholder="请输入手机号" class="input" />

        <!-- 新增字段 -->
        <select v-model="newPassenger.passengerType" class="input">
          <option value="" disabled>请选择乘客类型</option>
          <option value="0">成人</option>
          <option value="1">儿童</option>
          <option value="2">学生</option>
          <option value="3">特殊群体</option>
        </select>

        <select v-model="newPassenger.gender" class="input">
          <option value="" disabled>请选择性别</option>
          <option value="0">女</option>
          <option value="1">男</option>
        </select>
      </div>
      <div class="modal-footer">
        <button class="btn primary-btn" :disabled="!isFormValid" @click="submitPassenger">
          确认
        </button>
      </div>
    </div>
  </div>
  <!-- 选择已有乘客弹窗 -->
  <div v-if="showPassengerListModal" class="modal-overlay">
    <div class="modal">
      <button class="close" @click="showPassengerListModal = false">×</button>
      <div class="passenger-form-body">
        <div class="passenger-list-scroll">
          <div v-if="passengers === null" class="placeholder">正在加载乘客信息...</div>
          <div v-else-if="passengers.length === 0" class="placeholder">暂未保存任何信息</div>
          <div v-else>
            <div
              v-for="(p, index) in passengers"
              :key="index"
              class="passenger-item clickable"
              @click="selectPassenger(p)"
            >
              <p>
                <strong>姓名：{{ p.passengerName }}</strong>
              </p>
              <p>身份证：{{ p.idCardNumber }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 底部操作 -->
  <!-- “立即预定”按钮 -->
  <div class="footer-wrapper">
    <button class="btn primary-btn" @click="handleBookingClick">立即预定</button>
  </div>
  <!-- 支付弹窗 -->
  <PaymentModal
    :visible="showPaymentModal"
    :userName="userName"
    :price="Number(price) * selectedPassengers.length"
    :trainNumber="trainNumber"
    :seatType="seatType"
    :date="date"
    :passengerName="selectedPassengers.length > 0 ? selectedPassengers[0].name : ''"
    :passengerIdCard="selectedPassengers.length > 0 ? selectedPassengers[0].idCard : ''"
    @close="showPaymentModal = false"
    @success="handlePaymentSuccess"
    @fail="handlePaymentFail"
  />
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import PaymentModal from '@/components/PaymentModal.vue'

const goHome = () => {
  router.push('/home') // 返回首页路径
}
const route = useRoute()
const router = useRouter()
const userName = route.query.userName as string
const trainNumber = route.query.trainNumber as string
const from = route.query.from as string
const to = route.query.to as string
const duration = route.query.duration as string
const date = route.query.date as string
const seatType = route.query.seatType as string
const price = route.query.price as string

const showAddPassenger = ref(false)
const newPassenger = ref({
  name: '',
  idCard: '',
  phone: '',
  passengerType: '', // 默认为空，需要用户选择
  gender: '', // 默认为空，需要用户选择
})
const showPassengerListModal = ref(false)
const passengers = ref<{ passengerName: string; idCardNumber: string; phoneNumber: string }[]>([])
const selectedPassengers = ref<{ name: string; idCard: string }[]>([])
const showPaymentModal = ref(false)

// 获取用户信息的辅助函数
async function getUserInfo(userName: string) {
  try {
    const response = await fetch(
      `http://localhost:9000/api/users?username=${encodeURIComponent(userName)}`,
    )
    if (response.ok) {
      const userInfo = await response.json()
      return userInfo.userId || userInfo // 兼容不同的返回格式
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
  return null
}

async function fetchPassengers() {
  showPassengerListModal.value = true
  try {
    // 直接使用userName来获取用户ID，避免localStorage中的userId格式问题
    const actualUserId = await getUserInfo(userName)
    if (!actualUserId) {
      throw new Error('用户不存在')
    }

    console.log('使用的用户ID:', actualUserId)

    const res = await fetch(`http://localhost:9000/api/passengers/user/${actualUserId}`)
    if (!res.ok) throw new Error('请求失败')
    const data = await res.json()
    passengers.value = data
  } catch (error) {
    console.error('获取乘客信息失败:', error)
    passengers.value = [] // 显示"暂无信息"
  }
}
function selectPassenger(p: { passengerName: string; idCardNumber: string; phoneNumber: string }) {
  const exists = selectedPassengers.value.some(
    (sp) => sp.idCard === p.idCardNumber && sp.name === p.passengerName,
  )
  if (!exists) {
    selectedPassengers.value.push({ name: p.passengerName, idCard: p.idCardNumber })
  }
  showPassengerListModal.value = false
}
/*去除展示页面的乘客信息*/
function removePassenger(index: number) {
  selectedPassengers.value.splice(index, 1)
}
// 验证输入是否完整
const isFormValid = computed(
  () =>
    newPassenger.value.name &&
    newPassenger.value.idCard &&
    newPassenger.value.phone &&
    newPassenger.value.passengerType !== undefined &&
    newPassenger.value.gender !== undefined,
)
// 关闭弹窗
function closeModal() {
  showAddPassenger.value = false
  newPassenger.value.name = ''
  newPassenger.value.idCard = ''
  newPassenger.value.phone = ''
  newPassenger.value.passengerType = ''
  newPassenger.value.gender = ''
}
// 给后端传送新建的乘客信息
async function submitPassenger() {
  if (!isFormValid.value) return
  try {
    // 1. 先获取用户ID
    const userId = await getUserInfo(userName)
    if (!userId) {
      throw new Error('用户不存在')
    }

    // 2. 构建符合后端格式的数据
    const passengerRequest = {
      userId: userId,
      passengerName: newPassenger.value.name,
      idCardNumber: newPassenger.value.idCard,
      phoneNumber: newPassenger.value.phone,
      passengerType: newPassenger.value.passengerType
        ? parseInt(newPassenger.value.passengerType)
        : 0, // 转换为数字，默认为成人
      gender: newPassenger.value.gender ? parseInt(newPassenger.value.gender) : 0, // 转换为数字，默认为女性
      active: true,
    }

    // 3. 发送请求
    const res = await fetch('http://localhost:9000/api/passengers', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(passengerRequest),
    })
    if (!res.ok) {
      const errorData = await res.json()
      throw new Error(errorData.message || '提交失败')
    }

    selectedPassengers.value.push({
      name: newPassenger.value.name,
      idCard: newPassenger.value.idCard,
    })
    console.log('提交成功')
    closeModal()
    /*await fetchPassengers() /!*刷新乘客列表*!/*/
  } catch (error) {
    console.error('提交乘客信息失败:', error)
    alert('提交失败，请稍后重试')
  }
}
// 判断是否已选择乘客
function handleBookingClick() {
  if (selectedPassengers.value.length === 0) {
    alert('请至少添加一位乘客后再进行预定')
    return
  }
  showPaymentModal.value = true
}
// 处理支付成功或否
async function handlePaymentSuccess() {
  try {
    // 使用统一订单服务批量创建火车票订单
    const orders = selectedPassengers.value.map((p) => ({
      userName,
      trainNumber,
      seatType,
      date,
      name: p.name,
      idCard: p.idCard,
      price: Number(price),
    }))

    const res = await fetch('http://localhost:9000/api/orders/train-ticket/batch', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(orders),
    })
    if (!res.ok) {
      const errorData = await res.json()
      throw new Error(errorData.message || '订单提交失败')
    }

    const result = await res.json()
    if (result.success) {
      alert('支付成功，车票订单已生成，即将返回首页')
      // 支付成功后跳转
      router.push({
        path: '/home',
      })
    } else {
      throw new Error(result.message || '订单创建失败')
    }
  } catch (error: unknown) {
    console.error('提交订单失败:', error)
    const errorMessage = error instanceof Error ? error.message : '未知错误'
    alert(`订单提交失败: ${errorMessage}`)
  }
}
function handlePaymentFail(event: { status: string; message?: string }) {
  if (event.status === 'user_not_found') {
    alert('用户信息获取失败，请重新登录')
    // 跳转到登录页面
    router.push('/login')
  } else if (event.status === 'insufficient_balance') {
    alert('余额不足，请先充值')
    router.push('/wallet')
  } else {
    alert(`支付失败: ${event.message || '请检查网络连接或联系客服'}`)
  }
}
</script>

<style scoped>
body {
  margin: 0;
  padding-top: 0;
}
.section {
  max-width: 960px;
  margin: 24px auto 24px;
  background: #fff;
  padding: 16px 24px; /* 上下内边距由 24px 改为 16px */
  border-radius: 12px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}
.section h2 {
  font-size: 20px;
  margin-bottom: 16px;
}
.footer-wrapper {
  max-width: 960px;
  margin: 40px auto;
  text-align: center;
}

/*返回按钮*/
.back-home-btn {
  position: fixed;
  top: 20px;
  left: 20px;
  background-color: #3b82f6;
  color: white;
  border: none;
  padding: 8px 14px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  z-index: 998;
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
  transition: all 0.2s ease;
}
.back-home-btn:hover {
  background-color: #2563eb;
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 123, 255, 0.4);
}
.back-home-btn:active {
  transform: scale(0.98);
  box-shadow: 0 1px 4px rgba(0, 123, 255, 0.2);
}

/*顶部标题*/
.train-header {
  text-align: center;
  margin-top: 0;
  padding-top: 6px; /* 顶部内边距小一点 */
}
.train-header h1 {
  color: #0086f6;
  font-size: 28px;
  margin-bottom: 5px;
}
.subtitle {
  color: #666;
  font-size: 15px;
}

/*车次卡片布局*/
.train-card {
  background: #fff;
  padding: 16px 20px; /* 缩小内边距 */
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  max-width: 1000px; /* 更宽一点 */
  margin: 20px auto; /* 缩小外边距 */
}
.stations {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 12px 0;
}
.station {
  width: 160px;
  text-align: center;
  white-space: nowrap; /* 不换行 */
}
.city {
  font-size: 24px;
  font-weight: 600;
}
.train-middle {
  flex: 1;
  text-align: center;
  position: relative;
}
.duration {
  font-size: 14px;
  color: #555;
  margin-bottom: 6px;
}
.arrow-svg {
  width: 80px;
  height: 10px;
  margin: 0 auto;
  display: block;
}
.train-no {
  font-size: 14px;
  color: #555;
  margin-top: 6px;
}
.train-extra {
  display: flex;
  justify-content: center; /* 居中 */
  gap: 40px; /* 两项之间的间距 */
  font-size: 15px;
  color: #555;
  margin-top: 12px;
}

/*乘客信息*/
.section-header.column-layout {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}
.section-header.column-layout h2 {
  margin-top: 6px; /* 去掉顶部外边距 */
  margin-bottom: 12px;
}
.placeholder {
  color: #888;
  font-size: 14px;
  margin-top: 12px;
}
.passenger-brief {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 6px 10px;
  margin-bottom: 4px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background-color: #fafafa;
  font-size: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
  line-height: 1.3;
}
.passenger-brief strong {
  font-size: 18px;
  color: #111;
}
.passenger-brief p {
  margin: 2px 0;
  color: #888; /* 原本可能是 #333 或默认颜色，改成更淡的灰色 */
  font-size: 15px; /* 字号可稍微调小，增强主次 */
}
.passenger-display-scroll {
  max-height: 160px; /* 可根据页面实际情况调整 */
  overflow-y: auto;
  padding: 8px;
  border-radius: 6px;
}
.passenger-display-scroll::-webkit-scrollbar {
  width: 6px;
}
.passenger-display-scroll::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 4px;
}
.remove-btn {
  align-self: center; /* 保证垂直居中 */
  background: none;
  border: none;
  padding: 2px;
  margin-right: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  transition:
    color 0.2s ease,
    transform 0.2s ease;
  width: 28px;
  height: 28px;
  border-radius: 50%;
}
.remove-btn:hover {
  color: #e74c3c;
  background-color: rgba(231, 76, 60, 0.1);
  transform: scale(1.1);
}
.remove-btn svg {
  width: 20px;
  height: 20px;
}

/* 操作按钮 */
.btn {
  padding: 10px 16px; /* 更高一些 */
  font-size: 16px;
  border-radius: 6px;
  border: none;
  cursor: pointer;
  transition: all 0.3s ease; /* 平滑过渡 */
  width: 200px; /* 固定宽度 */
  text-align: center;
}
.btn:hover {
  background-color: #2563eb;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* 添加阴影 */
}
.add-btn {
  background-color: #3b82f6;
  color: #fff;
  font-weight: bold;
}
.select-btn {
  margin-top: 10px;
  background-color: #f3f4f6;
  color: #333;
  font-weight: bold;
}
.select-btn:hover {
  background-color: #e5e7eb;
}
.primary-btn {
  background-color: #3b82f6;
  color: #fff;
  font-weight: bold;
}

/* 添加乘客弹窗样式 */
.modal-overlay {
  position: fixed;
  inset: 0;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}
.modal {
  background: #fff;
  padding-top: 40px;
  padding-bottom: 80px;
  border-radius: 12px;
  width: 460px;
  position: relative;
  box-shadow: 0 6px 30px rgba(0, 0, 0, 0.2);
  max-height: 90vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
.passenger-form-body {
  flex: 1;
  padding: 0 30px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.input {
  padding: 12px;
  font-size: 15px;
  border: 1px solid #ccc;
  border-radius: 6px;
  width: 100%;
  box-sizing: border-box;
}

/* 为select元素添加特殊样式 */
.input[type='text'],
.input[type='text']:focus {
  outline: none;
  border-color: #3b82f6;
}

select.input {
  background-color: #fff;
  cursor: pointer;
}

select.input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

/* 禁用选项的样式 */
select.input option[disabled] {
  color: #999;
  font-style: italic;
}
.modal-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: center;
  background: #fff;
  padding: 10px 0;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
}
.btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
.close {
  position: absolute;
  top: 3px;
  right: 16px;
  font-size: 36px;
  background: none;
  border: none;
  cursor: pointer;
  color: #999;
}
.close:hover {
  color: #000;
}

/*选择乘客弹窗*/
.passenger-item {
  padding: 10px 14px;
  margin-bottom: 6px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: #fdfdfd;
  font-size: 13px;
  line-height: 1.4;
}
.passenger-item strong {
  font-size: 16px;
  color: #222;
}
.selected-passengers {
  margin-bottom: 12px;
  width: 100%;
}
.passenger-list-scroll {
  max-height: 300px;
  overflow-y: auto;
  padding-right: 6px; /* 给滚动条留点空隙 */
}
.passenger-list-scroll::-webkit-scrollbar {
  width: 6px;
}
.passenger-list-scroll::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 4px;
}
.passenger-item.clickable {
  cursor: pointer;
  transition: background 0.2s;
}
.passenger-item.clickable strong {
  font-size: 16px;
  color: #111;
}
.passenger-item.clickable p {
  margin: 2px 0;
  color: #888; /* 原本可能是 #333 或默认颜色，改成更淡的灰色 */
  font-size: 15px; /* 字号可稍微调小，增强主次 */
}
.passenger-item.clickable:hover {
  background-color: #f0f0f0;
}
</style>
